package com.example.shiro01.config;

import com.example.shiro01.dao.UserDao;
import com.example.shiro01.pojo.User;
import com.example.shiro01.service.imp.UserServiceImp;
import com.example.shiro01.util.jiam;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {


    @Autowired
    private UserServiceImp userServiceImp ;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=》授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo simpleAuthenticationInfo=new SimpleAuthorizationInfo();
        Subject subject= SecurityUtils.getSubject();
        User user=(User) subject.getPrincipal();

        String perm=user.getPerms();
        simpleAuthenticationInfo.addStringPermission(perm);

        return simpleAuthenticationInfo;
    }

    private jiam j;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=》认证doGetAuthenticationInfo");
        //创建令牌
        UsernamePasswordToken usertoken = (UsernamePasswordToken) authenticationToken;
        User user= userServiceImp.denglu(usertoken.getUsername());
        //判断传入的数据
        if (user==null){
            return null;//抛出异常 UnknownAccountException
        }
        System.out.println();
        //密码认证，shiro做
        return new SimpleAuthenticationInfo(user,user.getUserpwd(),ByteSource.Util.bytes(usertoken.getUsername()),"");
    }
}
